package pl.edu.agh.stock.parser.onet;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import pl.edu.agh.stock.data.IndexDataPoint;
import pl.edu.agh.stock.data.ValorDataPoint;
import pl.edu.agh.stock.parser.GPWTools;
import pl.edu.agh.stock.parser.StockParser;
import pl.edu.agh.stock.parser.exceptions.StockParseException;

public class OnetStockParser implements StockParser {

	public static final String REALTIME_COMPANIES = "http://gielda.onet.pl/indeksy-i-akcje,18633,101,100,notowania-csv-drukuj.csv?datetime=&sortBy=&sortType=";
	
	@Override
	public Map<String, IndexDataPoint> downloadLatestData()
			throws StockParseException {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					new URL(REALTIME_COMPANIES).openStream()));
			reader.readLine();
			Map<String, ValorDataPoint> all = new HashMap<String, ValorDataPoint>();
			while (true) {
				String line = reader.readLine();
				if (line == null) {
					break;
				}
				if (line.length() == 0) {
					continue;
				}
				String[] dataParts = line.replaceAll(" ", "")
						.replaceAll(",", ".").split(";");

				String name = dataParts[3];
				

				GregorianCalendar date = new GregorianCalendar();
				String[] timeParts = dataParts[2].split(":");
				date.set(Calendar.HOUR_OF_DAY, Integer.valueOf(timeParts[0]));
				date.set(Calendar.MINUTE, Integer.valueOf(timeParts[1]));
				date.set(Calendar.SECOND, 0);
				date.set(Calendar.MILLISECOND, 0);

				Date time = date.getTime();
				float currentValue = Float.valueOf(dataParts[4]);
				float referenceValue = Float.valueOf(dataParts[7]);
				float openingValue = Float.valueOf(dataParts[8]);
				float minValue = Float.valueOf(dataParts[9]);
				float maxValue = Float.valueOf(dataParts[10]);
				float salesVolume = Float
						.valueOf(dataParts[dataParts.length - 1]);

				all.put(name, new ValorDataPoint(name, time, currentValue,
						referenceValue, openingValue, minValue, maxValue,
						salesVolume));
			}
			Map<String, IndexDataPoint> ret = new HashMap<String, IndexDataPoint>();
			for (Entry<String, Set<String>> e: GPWTools.INDICES.entrySet()) {
				Map<String, ValorDataPoint> filtered = new HashMap<String, ValorDataPoint>();
				for (Entry<String, ValorDataPoint> f: all.entrySet()) {
					if (e.getValue().contains(f.getKey())) {
						filtered.put(f.getKey(), f.getValue());
					}
				}
				ret.put(e.getKey(), new IndexDataPoint(e.getKey(), new ArrayList<ValorDataPoint>(filtered.values())));
			}
			return ret;
		} catch (Exception e) {
			throw new StockParseException(e);
		}
	}
}
